package com.zzh.test1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * LockSupport实现唤醒线程 阻塞线程
 */
public class Test4 {
    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            System.out.println("t1 is waiting");
            LockSupport.park();
            System.out.println("t1 is waken up");
        }, "t1");
        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        Thread t2 = new Thread(() -> {
            LockSupport.unpark(t1);// 唤醒t1 发放许可
            System.out.println("t2 is notifying t1");
        });
        t2.start();

        //输出结果
        //t1 is waiting
        //t2 is notifying t1
        //t1 is waken up

        // 顺序交换依旧可以唤醒线程
        Thread t3 = new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }// 等待2秒 保证先执行 唤醒unpark(t3)
            System.out.println("t3 is waiting");
            LockSupport.park();
            System.out.println("t3 is waken up");
        }, "t3");
        t3.start();


        Thread t4 = new Thread(() -> {
            LockSupport.unpark(t3);// 唤醒t3 发放许可
            System.out.println("t4 is notifying t3");
        });
        t4.start();

        // 输出结果
        //t4 is notifying t3
        //t3 is waiting
        //t3 is waken up

    }
}
